import { customer } from "../../api";
import axios from "axios";

const MUTATION_TYPES = {
  CUSTOMER_LIST: "CUSTOMER_LIST",
  CUSTOMER_SIZE: "CUSTOMER_SIZE",
  CUSTOMER_DETAILS: "CUSTOMER_DETAILS",
  CUSTOMER_DETAILS_LABEL: "CUSTOMER_DETAILS_LABEL",
  DIALOG_VISIBLE: "DIALOG_VISIBLE"
};

const state = {
  customerList: [],
  totalCustomerSize: 0,
  customerDetails: {},
  customerDetailsLabel: [],
  dialogVisible: false
};
const getters = {};

const mutations = {
  [MUTATION_TYPES.CUSTOMER_LIST] (state, customerList) {
    state.customerList = customerList;
  },
  [MUTATION_TYPES.CUSTOMER_SIZE] (state, customerSize) {
    state.totalCustomerSize = customerSize;
  },
  [MUTATION_TYPES.CUSTOMER_DETAILS] (state, customerDetails) {
    state.customerDetails = customerDetails;
  },
  [MUTATION_TYPES.CUSTOMER_DETAILS_LABEL] (state, customerDetailsLabel) {
    state.customerDetailsLabel = customerDetailsLabel;
  },
  [MUTATION_TYPES.DIALOG_VISIBLE] (state, dialogVisible) {
    state.dialogVisible = dialogVisible;
  }
};

const actions = {
  async search ({ commit }, filter = {}) {
    let response = await customer.search(filter);
    if (response?.code === 0) {
      commit(MUTATION_TYPES.CUSTOMER_LIST, response.data?.records);
      commit(MUTATION_TYPES.CUSTOMER_SIZE, response.data?.total);
    }
  },
  async details ({ commit }, params) {
    const url = `${process.env.VUE_APP_URL}${params.url}/${params.customerId}`;
    let response = await axios.get(url);
    if (response?.code === 0) {
      commit(MUTATION_TYPES.CUSTOMER_DETAILS, response.data || {});
      commit(MUTATION_TYPES.DIALOG_VISIBLE, true);
    }
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
